import React, { createContext, useContext, useEffect, useState } from 'react';

interface ApiKeyContextType {
  stratzApiKey: string;
  setStratzApiKey: (key: string) => void;
  hasValidApiKey: boolean;
}

const ApiKeyContext = createContext<ApiKeyContextType | undefined>(undefined);

export const useApiKey = () => {
  const context = useContext(ApiKeyContext);
  if (context === undefined) {
    throw new Error('useApiKey must be used within an ApiKeyProvider');
  }
  return context;
};

interface ApiKeyProviderProps {
  children: React.ReactNode;
}

export const ApiKeyProvider: React.FC<ApiKeyProviderProps> = ({ children }) => {
  const [stratzApiKey, setStratzApiKeyState] = useState<string>(() => {
    // 从localStorage获取保存的API key
    const savedApiKey = localStorage.getItem('stratz_api_key');
    return savedApiKey || '';
  });

  useEffect(() => {
    // 保存API key到localStorage
    if (stratzApiKey) {
      localStorage.setItem('stratz_api_key', stratzApiKey);
    } else {
      localStorage.removeItem('stratz_api_key');
    }
  }, [stratzApiKey]);

  const setStratzApiKey = (key: string) => {
    setStratzApiKeyState(key.trim());
  };

  // 简单验证API key格式（JWT token格式）
  const hasValidApiKey = stratzApiKey.length > 0 && stratzApiKey.includes('.');

  const value = {
    stratzApiKey,
    setStratzApiKey,
    hasValidApiKey,
  };

  return (
    <ApiKeyContext.Provider value={value}>
      {children}
    </ApiKeyContext.Provider>
  );
};